import io

from fastapi import APIRouter, Request, Depends
from sqlalchemy.orm import Session
from starlette.responses import StreamingResponse

from common.auth.auth_interceptor import require_auth
from common.response.biz_response import R
from common.translate.biz_message import messages
from db.session import get_db
from model.dto.sys.login_token_dto import LoginTokenDto
from model.request.sys.login_request import LoginRequest
from model.request.sys.refresh_token_request import RefreshTokenRequest
from service_impl.sys.captcha_service_impl import CaptchaServiceImpl
from service_impl.sys.user_service_impl import UserServiceImpl

router = APIRouter()
CAPTCHA_KEY = "captchaKey"
user_service = UserServiceImpl()
captcha_service = CaptchaServiceImpl()


@router.get("/test", dependencies=[require_auth])
async def test_response() -> R:
    return R.success()


@router.post("/login")
async def login(login_request: LoginRequest, request: Request, db: Session = Depends(get_db)) -> R[LoginTokenDto]:
    session = request.session
    captcha_key = session.get(CAPTCHA_KEY)
    if captcha_key is not None:
        login_request.captcha_key = captcha_key
    tokens = user_service.login(db, login_request)
    return R.success(tokens, messages['LOGIN_SUCCESS'])


@router.get("/logout", dependencies=[require_auth])
async def logout():
    # 客户端应删除本地存储的令牌
    return R.success()


@router.get("/captcha")
async def captcha(request: Request):
    data, key = captcha_service.create()
    session = request.session
    session[CAPTCHA_KEY] = key
    return StreamingResponse(io.BytesIO(data.read()), media_type='image/png')


@router.post("/refresh/token")
async def refresh_access_token(request: RefreshTokenRequest, db: Session = Depends(get_db)):
    tokens = user_service.refresh_token(db, request.refresh_token)
    return R.success(tokens)
